import { Form, Input, Modal, message } from 'antd';
import { changePass } from '@/services/user'
type changePassType = {
    before?: string;
    after: string;
    confirm?: string;
};
type Props = {
    isModalOpen: boolean,
    setIsModalOpen: any
}

export default (props: Props) => {
    const { isModalOpen, setIsModalOpen } = props;
    const [changePassForm] = Form.useForm();
    const handleClose = () => {
        changePassForm.resetFields();
        setIsModalOpen(false)
    }
    const handleOk = () => {
        changePassForm.validateFields().then(async () => {
            const values = changePassForm.getFieldsValue()
            const result = await changePass({ before: values.before, after: values.after })
            if (result.code === 200) {
                message.success('修改成功')
                handleClose()
            } else {
                message.error(result.message);
            }
        }).catch(() => {
            console.log('error')
        })
    }

    return (
        <Modal title="修改密码" open={isModalOpen} onOk={handleOk} onCancel={handleClose} cancelText="取消" okText="确认">
            <Form
                form={changePassForm}
                name="changePass"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 16 }}

                autoComplete="off"
            >
                <Form.Item<changePassType>
                    label="原密码"
                    name="before"
                    rules={[{ required: true }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<changePassType>
                    label="新密码"
                    name="after"
                    rules={[{ required: true }]}
                >
                    <Input type='password' />
                </Form.Item>
                <Form.Item<changePassType>
                    label="确认密码"
                    name="confirm"
                    rules={[
                        { required: true },
                        ({ getFieldValue }) => ({
                            validator(rule, value) {
                                if (!value || getFieldValue('after') === value) {
                                    return Promise.resolve()
                                }
                                return Promise.reject("两次密码输入不一致")
                            }
                        })
                    ]}
                >
                    <Input type='password' />
                </Form.Item>
            </ Form>
        </Modal>
    )
}